package org.finesys.common.log.trace.interceptor.resttemplate;

import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.finesys.common.log.trace.interceptor.AbstractInterceptor;
import org.finesys.common.log.trace.util.LogstashUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

import static org.finesys.common.log.constants.TraceConstants.*;

@Slf4j
public class TraceIdRestTemplateInterceptor extends AbstractInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        HttpHeaders httpHeaders = request.getHeaders();
        String traceId = getTraceId();
        String spanId = getSpanId();
        String parentId = getParentId();
        try {
            if (StringUtils.isNotBlank(traceId)) {
                httpHeaders.add(TRACE_ID, traceId);
            } else {
                log.info(LogstashUtil.marker(), "current thread have not the traceId!");
            }
            if (StringUtils.isNotBlank(spanId)) {
                httpHeaders.add(SPAN_ID, spanId);
            }
            if (StringUtils.isNotBlank(parentId)) {
                httpHeaders.add(PARENT_ID, parentId);
            }

        } catch (Exception e) {
            log.error(LogstashUtil.exceptionMarker(), "RestTemplate http header set traceId exception!", e);
        }
        super.executeBefore(REST_TEMPLATE_EXEC_BEFORE);
        var response = execution.execute(request, body);
        super.executeAfter(REST_TEMPLATE_EXEC_AFTER);
        return response;
    }
}
